package com.distribution.system.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.distribution.common.core.controller.BaseController;
import com.distribution.common.core.domain.AjaxResult;
import com.distribution.common.core.domain.entity.SysUser;
import com.distribution.common.core.page.TableDataInfo;
import com.distribution.common.core.redis.RedisCache;
import com.distribution.common.utils.DictUtils;
import com.distribution.common.utils.StringUtils;
import com.distribution.common.utils.poi.ExcelUtil;
import com.distribution.system.domain.bo.*;
import com.distribution.system.domain.converter.CmccDaOrderWebConverter;
import com.distribution.system.domain.dto.ChoosePhoneDTO;
import com.distribution.system.domain.dto.CmccDaOrderListDTO;
import com.distribution.system.domain.dto.OrderStateDTO;
import com.distribution.system.domain.dto.PlaceOrderDTO;
import com.distribution.system.domain.entity.AddressSystem;
import com.distribution.system.domain.entity.CmccDaOrder;
import com.distribution.system.domain.entity.CmccDaProduct;
import com.distribution.system.domain.req.CmccDaOrderListExportReq;
import com.distribution.system.domain.req.CmccDaOrderListReq;
import com.distribution.system.domain.req.ReqResult;
import com.distribution.system.domain.vo.LineChartDataVO;
import com.distribution.system.mapper.SysUserMapper;
import com.distribution.system.service.AddressSystemService;
import com.distribution.system.service.CmccDaOrderService;
import com.distribution.system.service.CmccDaProductService;
import com.distribution.system.service.PlaceOrderOperationService;
import com.distribution.system.utils.EncryptionUtil;
import com.distribution.system.utils.convert.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * @author Liping Huo
 * @date 2023/5/22 21:24
 */
@RestController
@RequestMapping(value = "/cmccDaOrder")
@Slf4j
public class CmccDaOrderController extends BaseController {
    @Resource
    RedisCache redisCache;
    @Resource
    CmccDaOrderService cmccDaOrderService;
    @Resource
    CmccDaOrderWebConverter cmccDaOrderWebConverter;
    @Resource
    SysUserMapper sysUserMapper;
    @Resource
    PlaceOrderOperationService placeOrderOperationService;
    @Resource
    CmccDaProductService cmccDaProductService;
    @Resource
    AddressSystemService addressSystemService;

    /**
     * 订单管理页面 展示数据集
     *
     * @param cmccDaOrderListReq 订单管理页面请求参数
     * @return 数据列表
     */
    @PostMapping("/listCmccDaOrder")
    TableDataInfo listCmccDaOrder(@RequestBody CmccDaOrderListReq cmccDaOrderListReq) {
        CmccDaOrderListDTO cmccDaOrderListDTO = cmccDaOrderWebConverter.cmccDaOrderListReqToDto(cmccDaOrderListReq);
        startPage();
        List<CmccDaOrder> cmccDaOrders = cmccDaOrderService.listCmccDaOrder(cmccDaOrderListDTO);
        return getDataTable(cmccDaOrders);
    }
    @PostMapping("/listCmccDaOrderBySearchValue")
    TableDataInfo listCmccDaOrderBySearchValue(@RequestBody CmccDaOrderListReq cmccDaOrderListReq) {
        CmccDaOrderListDTO cmccDaOrderListDTO = cmccDaOrderWebConverter.cmccDaOrderListReqToDto(cmccDaOrderListReq);
        startPage();
        List<CmccDaOrder> cmccDaOrders = cmccDaOrderService.listCmccDaOrderBySearchValue(cmccDaOrderListDTO);
        return getDataTable(cmccDaOrders);
    }
    @PreAuthorize("@ss.hasAnyRoles('firstLevelAgent,secondLevelAgent,thirdLevelAgent')")
    @PostMapping("/getOrderStatusCount")
    ReqResult getOrderStatusCount(@RequestBody CmccDaOrderListReq cmccDaOrderListReq) {
        CmccDaOrderListDTO cmccDaOrderListDTO = cmccDaOrderWebConverter.cmccDaOrderListReqToDto(cmccDaOrderListReq);
        return ReqResult.success(cmccDaOrderService.getOrderStatusCount(cmccDaOrderListDTO));
    }
    @PreAuthorize("@ss.hasAnyRoles('firstLevelAgent,secondLevelAgent,thirdLevelAgent')")
    @PostMapping("/getOrderStatusCountBySearchValue")
    ReqResult getOrderStatusCountBySearchValue(@RequestBody CmccDaOrderListReq cmccDaOrderListReq) {
        CmccDaOrderListDTO cmccDaOrderListDTO = cmccDaOrderWebConverter.cmccDaOrderListReqToDto(cmccDaOrderListReq);
        return ReqResult.success(cmccDaOrderService.getOrderStatusCountBySearchValue(cmccDaOrderListDTO));
    }

    @PostMapping("/establishReported")
    TableDataInfo establishReported(@RequestBody CmccDaOrderListReq cmccDaOrderListReq) {
        CmccDaOrderListDTO cmccDaOrderListDTO = cmccDaOrderWebConverter.cmccDaOrderListReqToDto(cmccDaOrderListReq);
        startPage();
        List<CmccDaOrder> cmccDaOrders = cmccDaOrderService.listCmccDaOrder(cmccDaOrderListDTO);
        return getDataTable(cmccDaOrders);
    }

    /**
     * 订单管理页面 数据导出
     *
     * @param response           response
     * @param cmccDaOrderListExportReq cmccDaOrderListReq
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, CmccDaOrderListExportReq cmccDaOrderListExportReq) {
        CmccDaOrderListDTO cmccDaOrderListDTO = cmccDaOrderWebConverter.cmccDaOrderListExportReqToDto(cmccDaOrderListExportReq);
        List<CmccDaOrder> list = cmccDaOrderService.listCmccDaOrder(cmccDaOrderListDTO);
        Long userId = getUserId();
        //获取当前登录用户
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        if (sysUser.isOperationSupervisor()  || sysUser.isAdmin() || sysUser.isAgentOperation()) {
            List<CmccDaOrderInternalExportBO> cmccDaOrderExportBOS = BeanUtils.copyBeanCollection(CmccDaOrderInternalExportBO.class, list);
            cmccDaOrderExportBOS.forEach(f -> {
                String productStatus = f.getProductStatus() == null ? "-1" : f.getProductStatus();
                f.setProductStatusDesc(DictUtils.getDictLabel("order_product_status", productStatus));
            });
            ExcelUtil<CmccDaOrderInternalExportBO> util = new ExcelUtil<>(CmccDaOrderInternalExportBO.class);
            util.exportExcel(response, cmccDaOrderExportBOS, "订单数据");
        } else {
            List<CmccDaOrderExportBO> cmccDaOrderExportBOS = BeanUtils.copyBeanCollection(CmccDaOrderExportBO.class, list);
            cmccDaOrderExportBOS.forEach(f -> {
                String productStatus = f.getProductStatus() == null ? "-1" : f.getProductStatus();
                f.setProductStatusDesc(DictUtils.getDictLabel("order_product_status", productStatus));
            });
            ExcelUtil<CmccDaOrderExportBO> util = new ExcelUtil<>(CmccDaOrderExportBO.class);
            util.exportExcel(response, cmccDaOrderExportBOS, "订单数据");
        }
    }

    /**
     * 改变订单状态
     */
    @PostMapping("/updateOrderState")
    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    public AjaxResult updateOrderState(@RequestBody OrderStateDTO orderStateDTO){
        cmccDaOrderService.updateOrderState(orderStateDTO);
        return success();
    }

    @PostMapping("/updateOrderStatusByOrderNo")
    public AjaxResult updateOrderStatusByOrderNo(@RequestBody CmccDaOrder cmccDaOrder){
        cmccDaOrderService.updateOrderStatusByOrderNo(cmccDaOrder);
        return success();
    }

    @PostMapping("/updateOrderInfoByOrderNo")
    public AjaxResult updateOrderInfoByOrderNo(@RequestBody CmccDaOrder cmccDaOrder){
        cmccDaOrderService.updateOrderInfoByOrderNo(cmccDaOrder);
        return success();
    }

    @PostMapping("/updateOrderisWriteOff")
    public AjaxResult updateOrderisWriteOff(@RequestBody CmccDaOrder CmccDaOrder){
        cmccDaOrderService.updateOrderisWriteOff(CmccDaOrder);
        return success();
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<UnOrderImportBO> util = new ExcelUtil<>(UnOrderImportBO.class);
//        util.importTemplateExcel(response, "导入下单模板");
        List<UnOrderImportBO> unOrderImportBOS = new ArrayList<>();
        UnOrderImportBO unOrderImportBO = new UnOrderImportBO();
        unOrderImportBO.setCustomerName("张三");
        unOrderImportBO.setCustomerCertNo("371602xxxxxxxxxxxx");
        unOrderImportBO.setCustomerPhone("158xxxxxxxx");
        unOrderImportBO.setAddressProvince("河北");
        unOrderImportBO.setAddressCity("石家庄市");
        unOrderImportBO.setAddressArea("长安区");
        unOrderImportBO.setAddressStreet("万达小区一号楼二单元301");
        unOrderImportBO.setAttributeProvince("河北");
        unOrderImportBO.setAttributeCity("石家庄市");
        unOrderImportBOS.add(unOrderImportBO);
        util.exportExcel(response, unOrderImportBOS, "导入下单模板");
    }

    @PostMapping("/exportImportPlaceFail")
    public void exportImportPlaceFail(HttpServletResponse response)
    {
        List<UnOrderImportBO> unOrderImportFailedBOList = new ArrayList<>();
        List<Object> cacheList = redisCache.getCacheList("import_place_fail_list_" + getUserId());
        clearImportPlaceFailedCache();
        if (!cacheList.isEmpty()){
            cacheList.forEach(f -> {
                UnOrderImportBO unOrderImportBO = (UnOrderImportBO) f;
                unOrderImportFailedBOList.add(unOrderImportBO);
            });
        }
        ExcelUtil<UnOrderImportBO> util = new ExcelUtil<>(UnOrderImportBO.class);
        util.exportExcel(response, unOrderImportFailedBOList, "导入下单失败");
    }
    @PostMapping("/clearImportPlaceFailedCache")
    public void clearImportPlaceFailedCache()
    {
        redisCache.deleteObject("import_place_fail_list_" + getUserId());
    }
    @PreAuthorize("@ss.hasAnyRoles('firstLevelAgent,secondLevelAgent,thirdLevelAgent')")
    @PostMapping("/importUnOrder")
    public ReqResult importUnOrder(MultipartFile file, String productCode) {
        if (StringUtils.isBlank(productCode)) return ReqResult.error("请选择下单商品");
        String userId = EncryptionUtil.encodeBase64(String.valueOf(getUserId()));// 用户ID(base64加密)
        ExcelUtil<UnOrderImportBO> excelUtil = new ExcelUtil<>(UnOrderImportBO.class);
        List<UnOrderImportBO> unOrderImportBOList = new ArrayList<>();
        try {
            // 表格中读取数据
            unOrderImportBOList = excelUtil.importExcel(file.getInputStream());
        } catch (Exception e) {
            //throw new ServiceException("导入表格出错");
            return ReqResult.error("导入表格出错：" + e.getMessage());
        }
        if (unOrderImportBOList == null || unOrderImportBOList.isEmpty()) return ReqResult.error("读取表格数据为空");
        //System.out.println("unOrderImportBOList = " + unOrderImportBOList);
        // 根据商品编码查询商品信息
        CmccDaProduct cmccDaProduct = cmccDaProductService.getOne(new LambdaQueryWrapper<CmccDaProduct>().eq(CmccDaProduct::getProductCode, productCode));
        // 导入失败的订单集合
        List<UnOrderImportBO> unOrderImportFailedBOList = new ArrayList<>();
        log.info("开始多线程导入下单，时间：{}", LocalDateTime.now());
        long beginTime = System.currentTimeMillis();
        // 创建一个包含20个线程的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        // 存储每个任务的Future对象
        List<Future<UnOrderImportBO>> futures = new ArrayList<>();
        // 遍历下单
        for (UnOrderImportBO unOrderImportBO : unOrderImportBOList) {
            Callable<UnOrderImportBO> task = () -> {
                String customerName = unOrderImportBO.getCustomerName();
                String customerCertNo = unOrderImportBO.getCustomerCertNo();
                String customerPhone = unOrderImportBO.getCustomerPhone();
                // 根据归属地省市区名称查区划代码
                List<AddressSystem> attributeSystemList = addressSystemService.lambdaQuery()
                        .eq(AddressSystem::getProvinceName, unOrderImportBO.getAttributeProvince())
                        .eq(AddressSystem::getCityName, unOrderImportBO.getAttributeCity())
                        .list();
                // 根据收货地省市区名称查区划代码
                List<AddressSystem> addressSystemList = addressSystemService.lambdaQuery()
                        .eq(AddressSystem::getProvinceName, unOrderImportBO.getAddressProvince())
                        .eq(AddressSystem::getCityName, unOrderImportBO.getAddressCity())
                        .eq(AddressSystem::getDistrictName, unOrderImportBO.getAddressArea())
                        .list();
                if (attributeSystemList.isEmpty() || attributeSystemList.get(0) == null || addressSystemList.isEmpty() || addressSystemList.get(0) == null){
                    unOrderImportBO.setImportFailReason("归属地【" + unOrderImportBO.getAttributeProvince() + unOrderImportBO.getAttributeCity()
                             + "】或收货地址【" + unOrderImportBO.getAddressProvince() + unOrderImportBO.getAddressCity() + unOrderImportBO.getAddressArea() + "】与后台地址库不符");
                    return unOrderImportBO;
                }else {
                    // 归属地
                    AddressSystem attributeSystem = attributeSystemList.get(0);
                    String attributeProvinceName = attributeSystem.getProvinceName();
                    String attributeProvinceCode = attributeSystem.getProvinceCode();
                    String attributeCityName = attributeSystem.getCityName();
                    String attributeCityCode = attributeSystem.getCityCode();
                    // 收货地
                    AddressSystem addressSystem = addressSystemList.get(0);
                    String addressProvinceName = addressSystem.getProvinceName();
                    String addressProvinceCode = addressSystem.getProvinceCode();
                    String addressCityName = addressSystem.getCityName();
                    String addressCityCode = addressSystem.getCityCode();
                    String addressDistrictName = addressSystem.getDistrictName();
                    String addressDistrictCode = addressSystem.getDistrictCode();
                    String addressStreet = unOrderImportBO.getAddressStreet();
                    // 选购号码
                    String choosePhoneNum = null;
                    String uuid = null;
                    // 如果当前商品需要选号
                    if ("1".equals(cmccDaProduct.getSelectNumberFlag())){
                        // 配置选号信息
                        ChoosePhoneDTO choosePhoneDTO = new ChoosePhoneDTO();
                        choosePhoneDTO.setPage(1);
                        choosePhoneDTO.setProductCode(productCode);
                        choosePhoneDTO.setCertName(customerName);
                        choosePhoneDTO.setCertNum(customerCertNo);
                        choosePhoneDTO.setCustomerPhone(customerPhone);
                        choosePhoneDTO.setAttributeProvince(attributeProvinceName);
                        choosePhoneDTO.setAttributeProvinceCode(attributeProvinceCode);
                        choosePhoneDTO.setAttributeCity(attributeCityName);
                        choosePhoneDTO.setAttributeCityCode(attributeCityCode);
                        choosePhoneDTO.setAddressProvince(addressProvinceName);
                        choosePhoneDTO.setAddressProvinceCode(addressProvinceCode);
                        choosePhoneDTO.setAddressCity(addressCityName);
                        choosePhoneDTO.setAddressCityCode(addressCityCode);
                        choosePhoneDTO.setAddressDistrict(addressDistrictName);
                        choosePhoneDTO.setAddressDistrictCode(addressDistrictCode);
                        choosePhoneDTO.setAddressStreet(addressStreet);
                        // 选号
                        ReqResult reqResult = placeOrderOperationService.choosePhone(choosePhoneDTO);
                        if (reqResult.getCode() != 200){
                            unOrderImportBO.setImportFailReason(reqResult.getMsg());
                            return unOrderImportBO;
                        }else {
                            // 随机选取一个号码
                            ChoosePhoneResultBO choosePhoneResultBO = (ChoosePhoneResultBO) reqResult.getData();
                            List<String> numArray = choosePhoneResultBO.getNumArray();
                            choosePhoneNum = numArray.get(RandomUtil.randomInt(0, numArray.size()));
                            uuid = choosePhoneResultBO.getUuid();
                        }
                    }
                    // 配置下单信息
                    PlaceOrderDTO placeOrderDTO = new PlaceOrderDTO();
                    placeOrderDTO.setUserId(userId);
                    placeOrderDTO.setProductCode(productCode);
                    placeOrderDTO.setProductParam(cmccDaProduct.getProductParam());
                    placeOrderDTO.setProductTypeId(cmccDaProduct.getProductTypeId());
                    placeOrderDTO.setCustomerName(customerName);
                    placeOrderDTO.setCustomerCertNo(customerCertNo);
                    placeOrderDTO.setCustomerPhone(customerPhone);
                    placeOrderDTO.setAttributeProvince(attributeProvinceName);
                    placeOrderDTO.setAttributeProvinceCode(attributeProvinceCode);
                    placeOrderDTO.setAttributeCity(attributeCityName);
                    placeOrderDTO.setAttributeCityCode(attributeCityCode);
                    placeOrderDTO.setAddressProvince(addressProvinceName);
                    placeOrderDTO.setAddressProvinceCode(addressProvinceCode);
                    placeOrderDTO.setAddressCity(addressCityName);
                    placeOrderDTO.setAddressCityCode(addressCityCode);
                    placeOrderDTO.setAddressDistrict(addressDistrictName);
                    placeOrderDTO.setAddressDistrictCode(addressDistrictCode);
                    placeOrderDTO.setAddressStreet(addressStreet);
                    if ("1".equals(cmccDaProduct.getSelectNumberFlag())){
                        placeOrderDTO.setAttributeProvinceCode(addressProvinceCode);
                        placeOrderDTO.setAttributeCityCode(addressCityCode);
                        placeOrderDTO.setChoosePhone(choosePhoneNum);
                        placeOrderDTO.setPhoneUuid(uuid);
                    }
                    //System.out.println("unOrderDTO = " + unOrderDTO);
                    // 下单
                    placeOrderOperationService.placeOrder(placeOrderDTO);
                    return null;
                }
            };
            // 提交任务给线程池
            Future<UnOrderImportBO> future = executorService.submit(task);
            futures.add(future);
        }
        // 处理所有的Future对象，获取结果
        for (Future<UnOrderImportBO> future : futures) {
            try {
                // 获取任务执行的结果
                UnOrderImportBO unOrderImportBO = future.get();
                if (unOrderImportBO != null) {
                    unOrderImportFailedBOList.add(unOrderImportBO);
                }
            } catch (Exception e) {
                log.error("获取多线程结果异常", e);
            }
        }
        // 关闭线程池，不再接受新任务，已提交的任务将继续执行完毕
        executorService.shutdown(); // 关闭线程池，不再接受新任务，已提交的任务将继续执行完毕
        try {
            // 等待所有任务完成
            if (!executorService.awaitTermination(120, TimeUnit.SECONDS)) {
                executorService.shutdownNow(); // 强制关闭
            }else {
                log.info("多线程导入下单结束，时间：{}\n总耗时：{}毫秒", LocalDateTime.now(), (System.currentTimeMillis() - beginTime));
            }
        } catch (InterruptedException e) {
            log.error("多线程导入下单时线程异常" + e.getMessage());
            executorService.shutdownNow(); // 中断当前线程
        }
        if (!unOrderImportFailedBOList.isEmpty()){
            redisCache.setCacheList("import_place_fail_list_" + getUserId(), unOrderImportFailedBOList);
        }
        return unOrderImportFailedBOList.isEmpty() ? ReqResult.success("导入完成") : ReqResult.success(unOrderImportFailedBOList);
    }

    @PostMapping("/getTodayOrderCount")
    public ReqResult getTodayOrderCount(@RequestBody CmccDaOrderListReq cmccDaOrderListReq){
        LineChartDataVO lineChartDataVO = cmccDaOrderService.getTodayOrderCount(cmccDaOrderListReq);
        return ReqResult.success(lineChartDataVO);
    }

    @PostMapping("/getYesterdayOrderCount")
    public ReqResult getYesterdayOrderCount(@RequestBody CmccDaOrderListReq cmccDaOrderListReq){
        LineChartDataVO lineChartDataVO = cmccDaOrderService.getYesterdayOrderCount(cmccDaOrderListReq);
        return ReqResult.success(lineChartDataVO);
    }

    @PostMapping("/getWeekOrderCount")
    public ReqResult getWeekOrderCount(@RequestBody CmccDaOrderListReq cmccDaOrderListReq){
        LineChartDataVO lineChartDataVO = cmccDaOrderService.getWeekOrderCount(cmccDaOrderListReq);
        return ReqResult.success(lineChartDataVO);
    }

    @PostMapping("/getMonthOrderCount")
    public ReqResult getMonthOrderCount(@RequestBody CmccDaOrderListReq cmccDaOrderListReq){
        LineChartDataVO lineChartDataVO = cmccDaOrderService.getMonthOrderCount(cmccDaOrderListReq);
        return ReqResult.success(lineChartDataVO);
    }

    @PostMapping("/getCustomOrderCount")
    public ReqResult getCustomOrderCount(@RequestBody CmccDaOrderListReq cmccDaOrderListReq){
        LineChartDataVO lineChartDataVO = cmccDaOrderService.getCustomOrderCount(cmccDaOrderListReq);
        return ReqResult.success(lineChartDataVO);
    }

    @PostMapping("/batchImportOrder")
    public ReqResult batchImportOrder(@RequestBody String url, @RequestBody String channelInfoId){
        /*System.out.println("url = " + url);
        // 根据三方渠道名查询三方渠道ID
        List<CmccDaUpChannelInfo> list = cmccDaUpChannelInfoService.list(new LambdaQueryWrapper<CmccDaUpChannelInfo>()
                .eq(CmccDaUpChannelInfo::getChannelId, channelInfoId));
        if (list == null || list.isEmpty()){
            throw new ServiceException("渠道错误");
        }
        CmccDaUpChannelInfo cmccDaTripartiteInfo = list.get(0);
        ExcelUtil<CmccDaOrderImportBO> excelUtil = new ExcelUtil<>(CmccDaOrderImportBO.class);
        List<CmccDaOrderImportBO> cmccDaOrderBatchImportBOList = new ArrayList<>();
        try {
            // 表格中读取数据
            cmccDaOrderBatchImportBOList = excelUtil.importExcel(Files.newInputStream(Paths.get(url)));
            //cmccDaOrderBatchImportBOList = excelUtil.importExcel(Files.newInputStream(Paths.get("http://localhost/prod-api/profile/upload/2024/07/27/%E8%81%94%E9%80%9A%E6%9B%B4%E6%96%B0%E7%8A%B6%E6%80%81%E6%A8%A1%E6%9D%BF2_20240727151224A001.xlsx")));
        } catch (Exception e) {
            //throw new ServiceException("导入表格出错");
            return ReqResult.error("导入表格出错：" + e.getMessage());
        }
        if (cmccDaOrderBatchImportBOList == null || cmccDaOrderBatchImportBOList.isEmpty()) return ReqResult.error("读取表格数据为空");
        // 要插入的订单集合
        List<CmccDaOrder> importOrderList = new ArrayList<>();
        // 数据库中已经存在的当前渠道的订单编号集合
        List<CmccDaOrder> orderList = cmccDaOrderService.list(new LambdaQueryWrapper<CmccDaOrder>().eq(CmccDaOrder::getBindChannelInfoId, cmccDaTripartiteInfo.getChannelId()));
        List<String> orderIdList = orderList.stream().map(CmccDaOrder::getOrderId).collect(Collectors.toList());
        // 遍历表格读取到的数据，给各字段赋值
        for (CmccDaOrderImportBO bo : cmccDaOrderBatchImportBOList) {
            // 订单编号已存在的不插入
            if (orderIdList.contains(bo.getOrderId())) continue;

            CmccDaOrder cmccDaOrder = new CmccDaOrder();
            cmccDaOrder.setOrderId(bo.getOrderId());
            cmccDaOrder.setChannelOrderNo(bo.getChannelOrderNo());
            String userName = bo.getUserName();
            cmccDaOrder.setUserName(userName);
            SysUser sysUser = sysUserMapper.selectUserByUserName(userName);
            cmccDaOrder.setUserId(sysUser.getUserId());
            SysUser superiorSysUser = sysUserMapper.selectStaffUserById(sysUser.getUserId());
            cmccDaOrder.setSuperiorAgentId(superiorSysUser.getUserId());
            cmccDaOrder.setSuperiorAgentName(superiorSysUser.getUserName());
            cmccDaOrder.setProductName(bo.getProductName());
            // 下单商品
            CmccDaProduct cmccDaProduct = null;
            List<CmccDaProduct> productList = cmccDaProductService.list(new LambdaQueryWrapper<CmccDaProduct>().eq(CmccDaProduct::getProductName, bo.getProductName()));
            if (!productList.isEmpty()) {
                cmccDaProduct = productList.get(0);
                cmccDaOrder.setProductParam(cmccDaProduct.getProductParam());
                cmccDaOrder.setProductCode(cmccDaProduct.getProductCode());
            }
            cmccDaOrder.setCustomerName(bo.getCustomerName());
            cmccDaOrder.setCustomerCertNo(bo.getCustomerCertNo());
            cmccDaOrder.setCustomerAge(bo.getCustomerAge());
            cmccDaOrder.setAddress(bo.getAddress());
            cmccDaOrder.setAddressProvince(bo.getAddressProvince());
            cmccDaOrder.setAddressCity(bo.getAddressCity());
            cmccDaOrder.setAddressArea(bo.getAddressArea());
            cmccDaOrder.setAddressStreet(bo.getAddressStreet());
            cmccDaOrder.setCustomerPhone(bo.getCustomerPhone());
            cmccDaOrder.setChoosePhone(bo.getChoosePhone());
            cmccDaOrder.setChoosePhoneProvince(bo.getChoosePhoneProvince());
            cmccDaOrder.setChoosePhoneCity(bo.getChoosePhoneCity());
            boolean isSuccess = false;
            String orderStatus = "2";
            String orderStatusDesc = "进行中";
            switch (bo.getOrderStatusDesc()) {
                case "已成功":
                    orderStatus = "3";
                    orderStatusDesc = "已成功";
                    isSuccess = true;
                case "进行中":
                    orderStatus = "2";
                    orderStatusDesc = "进行中";
                case "失败":
                    orderStatus = "0";
                    orderStatusDesc = "失败";
            }
            if (cmccDaProduct != null) {
                DefaultProfitConditionEnum enumByCode = DefaultProfitConditionEnum.getEnumByCode(cmccDaProduct.getProfitConditionId());
                cmccDaOrder.setProfitConditionId(enumByCode.getCode());
                cmccDaOrder.setProfitConditionDesc(enumByCode.getCodeDesc());
                cmccDaOrder.setProfitConditionStatus(isSuccess ? "1" : "0");
                List<CmccDaProxyProductManage> cmccDaProxyProductManageList = cmccDaProxyProductManageService.list(new LambdaQueryWrapper<CmccDaProxyProductManage>().eq(CmccDaProxyProductManage::getUserId, sysUser.getUserId())
                        .eq(CmccDaProxyProductManage::getProductCode, cmccDaProduct.getProductCode()));
                if (!cmccDaProxyProductManageList.isEmpty()){
                    CmccDaProxyProductManage cmccDaProxyProductManage = cmccDaProxyProductManageList.get(0);
                    cmccDaOrder.setCommission(isSuccess ? cmccDaProxyProductManage.getCommission() : BigDecimal.ZERO);
                }
            }
            cmccDaOrder.setOrderStatus(orderStatus);
            cmccDaOrder.setOrderStatusDesc(orderStatusDesc);
            cmccDaOrder.setScMoney(bo.getScMoney());
            cmccDaOrder.setProductStatus(bo.getProductStatus());
            cmccDaOrder.setLimitTime(bo.getLimitTime());
            cmccDaOrder.setChannelOrderStatus(bo.getChannelOrderStatus());
            cmccDaOrder.setChannelOrderStatusMsg(bo.getChannelOrderStatusMsg());
            cmccDaOrder.setLogisticsInfo(bo.getLogisticsInfo());
            cmccDaOrder.setFailureReason(bo.getFailureReason());
            cmccDaOrder.setBindChannelInfoId();
            cmccDaOrder.setBindChannelInfoName();
        }*/
        // 集合不为空则执行sql插入
        return ReqResult.success();
    }

    @PostMapping("/batchOrderUpdateTemplate")
    public void batchOrderUpdateTemplate(HttpServletResponse response)
    {
        ExcelUtil<BatchOrderUpdateBO> util = new ExcelUtil<>(BatchOrderUpdateBO.class);
        util.importTemplateExcel(response, "批量更新订单模板");
    }
    @PreAuthorize("@ss.hasAnyRoles('operationSupervisor')")
    @PostMapping("/batchOrderUpdate")
    public ReqResult importOrderToUpdate(@RequestBody String url){
        ExcelUtil<CmccDaOrderBatchUpdateBO> excelUtil = new ExcelUtil<CmccDaOrderBatchUpdateBO>(CmccDaOrderBatchUpdateBO.class);
        /*// 根据三方渠道名查询三方渠道ID
        List<CmccDaTripartiteInfo> list = cmccDaTripartiteInfoService.list(new LambdaQueryWrapper<CmccDaTripartiteInfo>()
                .eq(CmccDaTripartiteInfo::getTripartiteName, tripartiteInfoId));
        if (list == null || list.isEmpty()){
            throw new ServiceException("渠道错误");
        }
        CmccDaTripartiteInfo cmccDaTripartiteInfo = list.get(0);*/
        List<CmccDaOrderBatchUpdateBO> cmccDaOrderBatchUpdateBOList = new ArrayList<>();
        try {
            // 表格中读取数据
            //cmccDaOrderBatchUpdateBOList = excelUtil.importExcel(Files.newInputStream(Paths.get(url)));
            cmccDaOrderBatchUpdateBOList = excelUtil.importExcel(Files.newInputStream(Paths.get("http://localhost/prod-api/profile/upload/2024/07/27/%E8%81%94%E9%80%9A%E6%9B%B4%E6%96%B0%E7%8A%B6%E6%80%81%E6%A8%A1%E6%9D%BF2_20240727151224A001.xlsx")));
        } catch (Exception e) {
            //throw new ServiceException("导入表格出错");
            return ReqResult.error("导入表格出错：" + e.getMessage());
        }
        if (cmccDaOrderBatchUpdateBOList == null || cmccDaOrderBatchUpdateBOList.isEmpty()) return ReqResult.error("读取表格数据为空");
        // 三方订单号集合
        List<String> channelOderNoList = cmccDaOrderBatchUpdateBOList.stream().map(CmccDaOrderBatchUpdateBO::getChannelOrderNo)
                .collect(Collectors.toList());
        // 根据三方订单号查询订单
        List<CmccDaOrder> cmccDaOrderList = cmccDaOrderService.list(new LambdaQueryWrapper<CmccDaOrder>().in(CmccDaOrder::getChannelOrderNo,channelOderNoList));
        if (cmccDaOrderList == null || cmccDaOrderList.isEmpty()){
            //throw new ServiceException("查询不到订单");
            return ReqResult.error("查询不到订单");
        }
        // 已更新的订单编号列表
        List<String> unUpdateOrderIdList = new ArrayList<>();
        // 遍历订单并修改
        for (CmccDaOrder cmccDaOrder : cmccDaOrderList) {
            List<CmccDaOrderBatchUpdateBO> cmccDaOrderBatchUpdateBOs = cmccDaOrderBatchUpdateBOList.stream()
                    .filter(x -> StringUtils.equals(x.getChannelOrderNo(), cmccDaOrder.getChannelOrderNo()))
                    .collect(Collectors.toList());
            // 如果没有符合条件的
            if (cmccDaOrderBatchUpdateBOs.isEmpty() || Objects.isNull(cmccDaOrderBatchUpdateBOs.get(0))){
                // 添加到未更新订单编号列表
                unUpdateOrderIdList.add(cmccDaOrder.getOrderId());
                continue;
            }
            CmccDaOrderBatchUpdateBO cmccDaOrderBatchUpdateBO = cmccDaOrderBatchUpdateBOs.get(0);
            RefreshOrderBO refreshOrderBO = new RefreshOrderBO();
            refreshOrderBO.setOrderId(cmccDaOrder.getOrderId());
            refreshOrderBO.setChannelOrderNo(cmccDaOrder.getChannelOrderNo());
            // 将首冲金额转换为分
            BigDecimal bigDecimal = new BigDecimal(cmccDaOrderBatchUpdateBO.getScMoney());
            refreshOrderBO.setScMoney(bigDecimal.multiply(BigDecimal.valueOf(100)).toString());
            String orderStatus = cmccDaOrderBatchUpdateBO.getOrderStatus();
            if ("成功关闭".equals(orderStatus)){
                refreshOrderBO.setStatus("3");
            }else if ("失败".equals(orderStatus)){
                refreshOrderBO.setStatus("-1");
            }else {
                refreshOrderBO.setStatus("2");
            }
            if (cmccDaOrderBatchUpdateBO.getRemark() != null) refreshOrderBO.setStatusMsg(cmccDaOrderBatchUpdateBO.getRemark());
            // 刷新订单状态
            cmccDaOrderService.refreshOrderStatusByRefreshOrderBO(cmccDaOrder, refreshOrderBO);
        }
        // 未更新的订单编号列表
        List<CmccDaOrderBatchUpdateBO> collect = cmccDaOrderBatchUpdateBOList.stream()
                .filter(x -> unUpdateOrderIdList.contains(x.getChannelOrderNo())).collect(Collectors.toList());
        new ExcelUtil<>(CmccDaOrderBatchUpdateBO.class).exportExcel(collect, "未更新订单编号");
        return ReqResult.success();
    }
}
